﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using System.Security.Cryptography;

namespace Core.Models
{

    #region Models

    public class ChangePasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class ChangeQuestionAnswerModel
    {
        [Required(ErrorMessage = "You have to provide the Password")]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string Password { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Current Security question")]
        public string Question { get; set; }

        [Required(ErrorMessage = "You have to provide a New Security Question")]
        [DataType(DataType.Text)]
        [Display(Name = "New Security Question")]
        [StringLength(127, ErrorMessage = "Security Question must be under 127 characters.")]
        public string SecurityQuestion { get; set; }

        [Required(ErrorMessage = "You have to provide an Answer")]
        [DataType(DataType.Text)]
        [Display(Name = "Answer")]
        [StringLength(127, ErrorMessage = "Answer must be under 127 characters.")]
        public string SecurityAnswer { get; set; }
    }

    public class LogOnModel
    {

        [Display(Name = "OpenID")]
        public string openid_identifier { get; set; }

        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }


    public class RegisterModel
    {
        [ScaffoldColumn(false)]
        public int RegistrationView { get; set; }

        [ScaffoldColumn(false)]
        public Guid BusinessUnitId { get; set; }

        [Required(ErrorMessage = "Email Address is required")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        [StringLength(127, ErrorMessage = "Email must be under 127 characters.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Security Code is required. You must have received this in an email.")]
        [StringLength(10, ErrorMessage = "Security code cannot be more than 10 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Security Code")]
        public string InviteCode { get; set; }

        [Required(ErrorMessage = "You have to choose an authentication method. If you are unsure about OpenID, please choose email & password.")]
        [Display(Name = "Authentication Method")]
        public bool UseOpenId { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "You have to provide a Security Question")]
        [DataType(DataType.Text)]
        [Display(Name = "Security Question")]
        [StringLength(127, ErrorMessage = "Security Question must be under 127 characters.")]
        public string SecurityQuestion { get; set; }

        [Required(ErrorMessage = "You have to provide a Security Answer")]
        [DataType(DataType.Text)]
        [Display(Name = "Security Answer")]
        [StringLength(127, ErrorMessage = "Security Answer must be under 127 characters.")]
        public string SecurityAnswer { get; set; }

        [Display(Name = "OpenID")]
        public string openid_identifier { get; set; }
    }

    public class ResetPasswordEmailModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Your email address")]
        [StringLength(127, ErrorMessage = "Email must be under 127 characters.")]
        public string Email { get; set; }
    }

    public class ResetPasswordAnswerModel
    {
        [DataType(DataType.Text)]
        [Display(Name = "Your Email address ")]
        public string Email { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Security question")]
        public string Question { get; set; }

        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Security answer")]
        [StringLength(127, ErrorMessage = "Security Answer must be under 127 characters.")]
        public string SecurityAnswer { get; set; }

        [Required]
        [ValidatePasswordLength]
        [DataType(DataType.Password)]
        [Display(Name = "New Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    #endregion

    #region Services
    // The FormsAuthentication type is sealed and contains static members, so it is difficult to
    // unit test code that calls its members. The interface and helper class below demonstrate
    // how to create an abstract wrapper around such a type in order to make the AccountController
    // code unit testable.

    public interface IMembershipService
    {
        int MinPasswordLength { get; }

        bool ValidateUser(string email, string password);
        MembershipCreateStatus CreateUser(string userName, string password, string email, string securityquestion, string securityanswer);
        bool ChangePassword(string email, string oldPassword, string newPassword);
        MembershipUser CreateOrGetUser(IAuthenticationResponse response);
    }

    public class AccountMembershipService : IMembershipService
    {
        private readonly MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public bool ValidateUser(string email, string password)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            return _provider.ValidateUser(email, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email, string securityquestion, string securityanswer)
        {
            //if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");

            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, securityquestion, securityanswer, true, null, out status);
            return status;
        }

        public bool ChangePassword(string email, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                MembershipUser currentUser = _provider.GetUser(email, true /* userIsOnline */);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public MembershipUser CreateOrGetUser(IAuthenticationResponse response)
        {
            MembershipUser user = _provider.GetUser(response.ClaimedIdentifier, true);
            if (user == null)
            {
                var claimsResponse = response.GetExtension<ClaimsResponse>();
                string email = null;
                string nickname = null;
                if (claimsResponse != null)
                {
                    email = claimsResponse.Email;
                    //fullName = claimsResponse.FullName;
                    nickname = claimsResponse.Nickname;
                }

                MembershipCreateStatus status;
                user = _provider.CreateUser(response.ClaimedIdentifier,
                    GenerateRandomString(64),
                    email,
                    "This is an OpenID account. You should log in with your OpenID.",
                    GenerateRandomString(64),
                    true,
                    null,
                    out status);
                if (status != MembershipCreateStatus.Success)
                {
                    throw new Exception("Failed to find or create user: " + status);
                }

                // TODO: set extra info in the profile, taking it from OpenID.
            }
            return user;
        }

        private static readonly RandomNumberGenerator CryptoRandomDataGenerator = new RNGCryptoServiceProvider();
        private static string GenerateRandomString(int length)
        {
            byte[] buffer = new byte[length];
            CryptoRandomDataGenerator.GetBytes(buffer);
            return Convert.ToBase64String(buffer);
        }
    }


    public interface IFormsAuthenticationService
    {
        void SignIn(string email, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string email, bool createPersistentCookie)
        {
            string BusinessUnitId = HttpContext.Current.Session["BusinessUnitId"].ToString();
            string BusinessUnitName = HttpContext.Current.Session["BusinessUnitName"].ToString();
            if (BusinessUnitId == Guid.Empty.ToString())
            {
                throw new Exception("Business Unit not defined");
            }
            string userDataString = String.Format("{0}|{1}",BusinessUnitId, BusinessUnitName);
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email"); 
            HttpCookie authcookie = FormsAuthentication.GetAuthCookie(email, createPersistentCookie);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcookie.Value);
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);
            authcookie.Value = FormsAuthentication.Encrypt(newTicket);
            HttpContext.Current.Response.Cookies.Add(authcookie);
            //FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
    #endregion

    #region Validation
    public static class AccountValidation
    {
        public static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
    {
        private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;

        public ValidatePasswordLengthAttribute()
            : base(_defaultErrorMessage)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
                name, _minCharacters);
        }

        public override bool IsValid(object value)
        {
            string valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= _minCharacters);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[]{
                new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
            };
        }
    }
    #endregion

}
